<?php
namespace Tool\mp4;
use FFMpeg\Coordinate\Dimension;
use FFMpeg\Coordinate\FrameRate;
use FFMpeg\Coordinate\TimeCode;
use FFMpeg\FFMpeg;
use FFMpeg\FFProbe;
use FFMpeg\Filters\Video\ResizeFilter;
use FFMpeg\Filters\Video\RotateFilter;
use FFMpeg\Format\Video\X264;

class Mp4
{
    // FFmpeg
    private $FFmpeg = null;

    // 视频对象
    private $Video = null;

    // 视频信息对象
    private $Info = null;

    // 文件绝对路径
    private $_file;

    // 视频宽度
    private $_width = 0;

    // 视频高度
    private $_height = 0;

    // 转码视频填充模式
    private $_model = ResizeFilter::RESIZEMODE_INSET;

    // 视频时长
    private $_duration = 0;

    public function __construct($_file)
    {
        $this->_file = $_file;
        $this->info();
        $this->FFmpeg = FFMpeg::create(KUYUAN_FFMPEG);
        $this->Video = $this->FFmpeg->open($this->_file);
    }

    public function __get($name)
    {
        return $this->$name;
    }

    /**
     * 获取视频信息
     */
    private function info()
    {
        $FFprobe = FFProbe::create(KUYUAN_FFMPEG);
        $this->Info = $FFprobe->streams($this->_file)
            ->videos()
            ->first();
        $this->_width = $this->Info->get("width");
        $this->_height = $this->Info->get("height");
        $this->_duration = $this->Info->get("duration");
    }

    /**
     * 生成视频封面
     * @param $_path 相对路径
     * @param int $_width 封面宽度
     * @return string 返回封面相对路径
     */
    public function thumb($_path,$_width = 720)
    {
      $_absolute_path = ATTACHMENT_ROOT.$_path;
      $this->Video->frame(TimeCode::fromSeconds(1))->save($_absolute_path);
      file_image_thumb($_absolute_path,$_absolute_path,$_width);
      return $_path;
    }

    /**
     * 转码
     * @param $_path
     * @param int $_width
     * @param int $_height
     * @return mixed
     */
    public function save($_path,$_width = 720,$_height = 1280)
    {
        $this->Video->filters()
            ->framerate(new FrameRate(30),60)
            ->synchronize();
        if($this->_width > $_width) {
            $this->correct();
            $this->Video->filters()->resize(new Dimension($_width,$_height),$this->_model);
        }
        $_absolute_path = ATTACHMENT_ROOT.$_path;
        $format = new X264("aac");
        $format->setKiloBitrate(1200);
        $format->setAudioKiloBitrate(127);
        $format->setAudioChannels(2);
        $this->Video->save($format,$_absolute_path);
        return $_path;
    }

    /**
     * 旋转矫正视频,视频转码的宽高计算
     */
    private function correct()
    {
        $_tags = $this->Info->get("tags");
        if(isset($_tags["rotate"]) && $_tags["rotate"] == 90){
            $this->_model = ResizeFilter::RESIZEMODE_FIT;
        }
    }
}